/**
 * Created by 01 on 2017/6/22.
 */
import cfg from '../config';
import * as ajax from '../lib/kajax';
import { Slider, sliderHide, sliderShow } from '../lib/kslider';
import { loadTrainCityLib } from '../lib/ktrainCity';
import { formatDate, getCurrDay, randomColor, isArrContain, isArrNoContain, findStr, backPage, getPrevDate, getNextDate, isSelector, message, closeMsg, getPinYin, getPassengers, strfind, hideIdcard, isEmptyObj, getJingTinInfoFun, tabSwitch, cityDataCache, getTrainCityFun } from '../util/aid';

import Dialog from '../lib/kdialog';
const dialog = new Dialog();

const $ = require('../lib/kdom');

// 获得席位和价格
// @param obj {id:'',...} 当前车次信息
// 返回 ['硬座,220',...]
function getSeatParam(obj) {
  // console.log(obj);
  let rc = [];
  let price = null;
  let yuPiao = null;
  let seat = null;
  let seatCode = null;
  const arr = ['WZ', 'YZ', 'RZ', 'RZ2', 'RZ1', 'YWS', 'YWZ', 'YWX', 'RWS', 'RWX', 'GWS', 'GWX', 'SWZ', 'TDZ'];
  const arr1 = ['无座', '硬座', '软座', '二等软座', '一等软座', '硬卧上', '硬卧中', '硬卧下', '软卧上', '软卧下', '高级软卧上', '高级软卧下', '商务座', '特等座'];
  let currKey = '';
  for (let key in obj) {
    for (let x = 0, len = arr.length; x < len; x++) {
      if (key === arr[x]) {
        if (key === 'YWS', key === 'YWZ', key === 'YWX') {
          currKey = key.substring(0, 2);
        } else if (key === 'RWS', key === 'RWX') {
          currKey = key.substring(0, 2);
        } else if (key === 'GWS', key === 'GWX') {
          currKey = key.substring(0, 2);
        } else {
          currKey = key;
        }
        // console.log('currKey', currKey);

        if (obj[key] !== '-' && obj[`${currKey}_YP`] > '0') {
          // if (obj[key] !== '-') {
          price = obj[key];
          yuPiao = obj[`${currKey}_YP`];
          seat = arr1[x];
          seatCode = obj[`${currKey}_CODE`];
          rc.push({ price: price, yuPiao: yuPiao, seat: seat, seatCode: seatCode });
        }
      }
    }
  }
  return rc;
}

// 设置列表详情和填写订单页面的头部信息
// @param data 当前车次信息
// @param opts 父页面参数
// @param tag 盒子
function setHeadTrianInfo(data, opts, tag) {
  // console.log(data, opts, tag);
  if (data && opts && tag) {
    let rc = `<li class="card" style="background:0;">
                <div class="card-content">
                    <div class="card-content-inner">
                        <div class="from">${data.StartCity}</div>
                        <div>${data.StartTime}</div>
                        <div>${opts.date}</div>
                    </div>
                    <div class="card-content-inner">
                        <h3 style="position: relative;top:-.4rem;">${data.TrainCode}</h3>
                         <span class="jt-info" id="jingTingInfo" style="position: relative;top:-.4rem;"></span>
                    </div>
                    <div class="card-content-inner">
                        <div class="to">${data.EndCity}</div>
                        <div class="to-time">${data.EndTime}</div>
                        <div>${data.CostTime}</div>
                    </div>
                </div>
            </li>`;
    $.html(tag, rc);
  }
}

/*$.qu('#pg-train-order-query .jt-info').onclick = () => {
 dialog.loading();
 loadJingTinInfoFun(jingTinInfo);
 sliderShow();
 };*/
function loadJingTinInfoFun(data) {
  if (!data) return;
  let temp = '';
  // console.log(data);
  let Train = data.data.TrainInfo.Train;
  for (let j = 0, o = data.data.TrainInfo.Stations.StationInfo; j < o.length; j++) {
    // console.log(o[j]);
    if (j === 0) {
      temp += `<li>
            <span>${j + 1}</span>
            <span>${o[j].StationName}</span>
            <span>始发</span>
            <span>${Train.FromTime}</span>
            <span>--</span>
         </li>`;
    } else if (j === (o.length - 1)) {
      temp += `<li>
            <span>${j + 1}</span>
            <span>${o[j].StationName}</span>
            <span>${Train.ArriveTime}</span>
            <span>到达</span>
            <span>--</span>
         </li>`;
    } else {
      temp += `<li>
            <span>${j + 1}</span>
            <span>${o[j].StationName}</span>
            <span>${o[j].ArriveTime}</span>
            <span>${o[j].DepartTime}</span>
            <span>${o[j].StayMinutes}</span>
         </li>`;
    }
  }
  let rc = `<br>
          <h3 class="text-center"><span class="icon icon-left float-left fwn pl075 text-disabled" id="JT_closeInfo">返回</span> 列车时刻表</h3>
          <ul class="jingtin-info tlt">
            <li>
              <span>站次</span>
              <span>车站</span>
              <span>到达</span>
              <span>发车</span>
              <span>停留</span>
            </li>
          </ul>
          <div class="jingtin-info-list">
            <ul class="jingtin-info">
            ${temp}
            </ul>
          </div>
          <br>`;
  new Slider({ content: rc });
  JT_closeInfo.onclick = () => {
    sliderHide();
  };
}

function orderGaiQianFun(data, cb) {
  // console.log('orderGaiQianFun', data);
  let rc = {
    from: null,
    to: null,
    ticketnos: null
  };
  let ticketnos = '';
  let tickets = data.orderRCAll ? JSON.parse(data.orderRCAll) : '';
  tickets = tickets.data ? tickets.data.Tickets : '';

  if (tickets && tickets.length > 0) {
    for (let j = 0, o = tickets, len = o.length; j < len; j++) {
      ticketnos += ticketnos !== '' ? `,${o[j].TicketNo}` : o[j].TicketNo;
    }
  }
  rc.ticketnos = ticketnos;
  getTrainCityFun(function (rs) {
    if (rs && data) {
      // console.log(rs, data);
      for (let j = 0, o = rs, len = o.length; j < len; j++) {
        if (data.fromstation == o[j]['StationName']) {
          rc.from = o[j];
        } else if (data.tostation == o[j]['StationName']) {
          rc.to = o[j];
        }
      }
      if (cb instanceof Function) cb(rc);
    }
  })
}

// 选中城市
function bindCityFun(tid, key) {
  // console.log(tid);
  let fromTag = $.qu(`#${tid.id} .from`); //目的地
  let toTag = $.qu(`#${tid.id} .to`); //出发地

  fromTag.onclick = () => {
    if (key) return;
    loadTrainCityLib({ prnTid: '#city', tag: '.from', from: fromTag.getAttribute('data-city'), to: toTag.getAttribute('data-city') });
    sliderShow();
    searchCityFun(fromTag, toTag, '.from');
  };

  toTag.onclick = () => {
    loadTrainCityLib({ prnTid: '#city', tag: '.to', from: fromTag.getAttribute('data-city'), to: toTag.getAttribute('data-city') });
    sliderShow();
    searchCityFun(fromTag, toTag, '.to');
  };
}

function searchCityFun(fromTag, toTag, elem) {
  /*searchCity.onkeyup = () => {
   $.addClass(searchCity.parentNode.parentNode, 'active');
   blurQueryFun();
   };*/
  /*  searchCity.onchange = () => {
   $.addClass(searchCity.parentNode.parentNode, 'active');
   blurQueryFun();
   if (blurQueryBox.innerHTML === '') {
   message('#blurQueryBox', '没有相关数据！');
   }
   };*/

  searchCityBtn.onclick = () => {
    searchCityCancel.style.display = 'block';
    $.addClass(searchCity.parentNode.parentNode, 'active');
    blurQueryFun(fromTag, toTag, elem);
    if (blurQueryBox.innerHTML === '') {
      message('#blurQueryBox', '没有相关数据！');
    }
  };
  searchCityCancel.onclick = () => {
    searchCityCancel.style.display = 'none';
    $.removeClass(searchCityCancel.parentNode, 'active');
    searchCity.value = '';
    cityContainer.style.display = 'block';
    $.html(blurQueryBox, '');
  };
}

// 模糊查询
function blurQueryFun(fromTag, toTag, elem) {
  $.html(blurQueryBox, '');
  let val = searchCity.value;
  let data = cityDataCache();
  if (!data) return;
  cityContainer.style.display = 'none';
  // const reg = new RegExp(`(^${val}*)`);
  let _a = null;
  let cityCode = null;
  let cityNmae = null;
  let opts = { prnTid: '#city', tag: elem, from: fromTag.getAttribute('data-city'), to: toTag.getAttribute('data-city') };

  for (let j = 0, o = data, len = o.length; j < len; j++) {
    console.log(o[j].StationName.indexOf(val));

    if (o[j].StationName.indexOf(val) > -1 || o[j].StationFullName.indexOf(val) === 0) {
      cityCode = o[j].StationCode;
      cityNmae = o[j].StationName;
      _a = document.createElement('a');
      _a.className = `city-item`;
      _a.setAttribute('data-city', `${cityCode},${cityNmae}`);
      _a.setAttribute('data-opt', `${JSON.stringify(opts)}`);
      _a.innerHTML = o[j]['StationName'];
      blurQueryBox.appendChild(_a);
    }
  }
}

// 查询日期
function queryDateFun(tid, date, cb) {
  let rc = localStorage.getItem(cfg.train.queryDate);
  let _date = date ? date : rc ? rc : new Date(); // 查询日期
  if (new Date(_date) < new Date()) { _date = new Date(); }
  // console.log('查询日期_date', _date);
  if (tid) {
    tid.value = formatDate('yyyy-MM-dd', _date);
  }
  if (cb) cb();
}

// starDateValFun
function starDateValFun(starDateVal, startDateTxt, cb) {
  starDateVal.onchange = () => {
    let queryDate = starDateVal.value;
    if (new Date(starDateVal.value) < new Date()) return dialog.alert({ content: '尊敬的旅客：请选择大于当前的日期！' });
    $.html(startDateTxt, getCurrDay(new Date(queryDate)));
    if (cb) cb();
  };
}

// 查询城市
function cityViewFun(tag, obj) {
  /*
   <div class="from" data-city="CQW,重庆">重庆</div>
   <div class="icon-chage"><span id="iconChage"><i></i></span></div>
   <div class="to" data-city="BJP,北京">北京</div>
   * */
  let rc = ` <div class="from" data-city="${obj.from}">${obj.from.split(',')[1]}</div>
             <div class="icon-chage"><span id="${tag.id}IconChage"><i></i></span></div>
             <div class="to" data-city="${obj.to}">${obj.to.split(',')[1]}</div>`;
  $.html(tag, rc);
}

function concelOrder(OrderNumber) {
  dialog.confirm({ content: '您好！您确定要取消订单吗？' }, (rs) => {
    if (rs) {
      dialog.loading();
      const formData = `action=cancleorder&orderno=${OrderNumber}`;
      console.log(formData);
      // 测试
      ajax.get(`${cfg.train.host}${cfg.train.getAct}`, formData, (rs) => {
        if (rs) {
          dialog.close();
          // console.log(rs);
          let r = JSON.parse(rs);
          if (r.successcode === 'T') {
            dialog.alert({ content: '取消成功！' }, () => {
              $.router.go('/train/order', '', true);
            });
          } else {
            dialog.alert({ content: r.Info || '非常抱歉，订单取消失败，请刷新或者退出重试！' }, () => {
              $.router.go('/train/order', '', true);
            });
          }
        }
      });
    } else {
      // dialog.alert({content: '非常抱歉，订单取消失败，请刷新或者退出重试！'}, () => {
      //   $.router.go('/train/order', '', true);
      // });
    }
  });
}

function changeSignOrder(orderInfo) {
  let _opts = null;
  orderGaiQianFun(orderInfo, (rs) => {
    _opts = { from: `${rs.from.StationCode},${rs.from.StationName}`, to: `${rs.to.StationCode},${rs.to.StationName}`, date: formatDate('yyyy-MM-dd', orderInfo.sdate), keyword: 'changeapply', orderNo: orderInfo.outOrderID, ticketnos: rs.ticketnos };
    $.router.go('/train/change-sign', _opts, true);
  });
}
function refundsOrder(OrderNumber, ticketnos) {
  dialog.confirm({ content: '您好！您确定要退票吗？' }, (rs) => {
    if (rs) {
      dialog.loading();
      const formData = `action=refund&orderno=${OrderNumber}&ticketnos=${ticketnos}`;
      console.log(formData);
      // 测试
      ajax.get(`${cfg.train.host}${cfg.train.getAct}`, formData, (rs) => {
        if (rs) {
          dialog.close();
          // console.log(rs);
          let r = JSON.parse(rs);
          if (r.successcode === 'T') {
            dialog.alert({ content: '申请退票成功！' }, () => {
              $.router.go('/train/order', '', true);
            });
          } else {
            dialog.alert({ content: r.Info || '非常抱歉，订单取消失败，请刷新或者退出重试！' }, () => {
              $.router.go('/train/order', '', true);
            });
          }
        }
      });
    } else {
      // dialog.alert({content: '非常抱歉，订单取消失败，请刷新或者退出重试！'}, () => {
      //   $.router.go('/train/order', '', true);
      // });
    }
  });
}

function findOrderDelData(orderData, idx) {
  let rc = {};
  let orderInfo = orderData.orderInfo;
  let passengerInfo = orderData.passengerInfo;

  for (let i = 0; i < orderInfo.length; i++) {
    if (orderInfo[i].orderID == idx) {
      rc.orderInfo = orderInfo[i]
    }
  }

  for (let j = 0; j < passengerInfo.length; j++) {
    if (passengerInfo[j].orderID == idx) {
      rc.passengerInfo = passengerInfo[j]
    }
  }
  return rc;
}

function getTicketnosStr(rs) {
  if (!rs) return;
  let rc = [];
  for (let i = 0; i < rs.length; i++) {
    rc.push(rs[i].TicketNo);
  }
  return rc;
}

function payorderFun(_order, _data, _opts, _currSaet) {
  dialog.loading();
  const formData = `action=confirmpayorder&orderno=${_order.OrderNumber}&price=${_order.OrderAmount}`;
  console.log(formData);
  // 测试
  ajax.get(`${cfg.train.host}${cfg.train.getAct}`, formData, (rs) => {
    if (rs) {
      dialog.close();
      console.log(rs);
      let r = JSON.parse(rs);
      if (r.successcode === 'T') {
        dialog.close();
        $.router.go('/train/pay-result', { data: _data, opts: _opts, order: _order, result: r, currSaet: _currSaet }, true);
      } else {
        dialog.close();
        dialog.alert({ content: r.Info || '非常抱歉，订单支付失败，请刷新或者退出重试！' }, () => {
          $.router.go('/train/pay-result', { data: _data, opts: _opts, order: _order, result: r, currSaet: _currSaet }, true);
        });
      }
    }
  });
}

export { getSeatParam, setHeadTrianInfo, loadJingTinInfoFun, orderGaiQianFun, queryDateFun, starDateValFun, cityViewFun, bindCityFun, findOrderDelData, refundsOrder, changeSignOrder, concelOrder, getTicketnosStr, payorderFun };